package com.cu.jiekong.mqhandler;

import com.alibaba.fastjson.JSON;
import com.cu.jiekong.constants.ResultStatus;
import com.cu.jiekong.frame.model.Ret;
import com.cu.jiekong.model.BorrowAuditorInfo;
import com.cu.jiekong.model.BorrowInfo;
import com.cu.jiekong.model.User;
import com.cu.jiekong.service.AppUserService;
import com.cu.jiekong.service.AuditorService;
import com.cu.jiekong.service.BorrowAuditorInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jintian
 * @date 16:06
 */
@Component
@RabbitListener(queues = "borrowInfo")
public class BorrowInfoRiskHandler {

    private Logger logger = LoggerFactory.getLogger(BorrowInfoRiskHandler.class);


    @Autowired
    private BorrowAuditorInfoService borrowAuditorInfoService;

    @Autowired
    private AuditorService auditorService;

    @Autowired
    private AppUserService userService;

    /**
     * 评审借款订单
     *
     * @param msg
     */
    @RabbitHandler
    public void auditorBorrow(String msg) {
        logger.info(" get msg :" + msg);
        // 将需要审核的借款存库
        BorrowInfo borrowInfo = JSON.parseObject(msg, BorrowInfo.class);
        // 根据借款信息生成审核信息表
        BorrowAuditorInfo borrowAuditorInfo = new BorrowAuditorInfo(borrowInfo);
        // 连接远端获取用户信息
        Ret ret = userService.getAppUserById(borrowAuditorInfo.getBorrowUser() + "");

        // 错误则重试3次
        for (int i = 0; !ResultStatus.RESULT_000000.getCode().equals(ret.getCode()) && i < 3; i++) {
            logger.info(" get user has error ,errorCode : " + ret.getCode() + " errorMsg :" + ret.getMessage() + " i = " + i);
            ret = userService.getAppUserById(borrowAuditorInfo.getBorrowUser() + "");
        }
        if (!ResultStatus.RESULT_000000.getCode().equals(ret.getCode())) {
            // TODO 发送报告给mannger通知
            return;
        }
        User user = (User) ret.getData();
        borrowAuditorInfo.setBorrowUserName(user.getUserName());
        borrowAuditorInfo.setBorrowUserIdentId(user.getUserId());
        borrowAuditorInfo.setBorrowUserMobile(user.getUserPhone());
        // 添加需要审核的借款信息
        borrowAuditorInfoService.insertBorrowAuditorInfo(borrowAuditorInfo);
        // 机器初步审核（机审）
        auditorService.auditorBorrow(borrowAuditorInfo);
    }
}
